#! _*_ coding: utf8 _*_
import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import api_view

from starday.models import SDEvent
from starday.serializers import SDEventSeri, SDRichPartSeri
from tools.err import RoingException
from tools.util import merge_list


@api_view(['POST'])
def add_event(request):
    seri = SDEventSeri(data=request.data)
    if seri.is_valid():
        event = seri.save()
        parts_json = json.loads(request.data.get('parts', '[]'))
        for part in parts_json:
            if len(part['text'].strip('\n')) == 0: continue

            part['event'] = event.pk
            part_seri = SDRichPartSeri(data=part)
            if part_seri.is_valid():
                part_obj = part_seri.save()
                part_obj.save()
            else:
                print(part_seri.errors)
    else:
        return JsonResponse({'error': str(seri.errors)})
    return JsonResponse(seri.data)


@api_view(['GET'])
def events(request):
    params = request.query_params
    date_str = params.get('date_str', '')
    page = int(params.get('page', 0))
    limit = int(params.get('limit', 30))

    if not date_str:
        raise RoingException(code=611, message=u'无效的参数')

    all_events = SDEvent.objects.filter(date_str=date_str)
    events_map = {}
    for event in all_events:
        events = events_map.get(event.category.title, [])
        events.append(event)
        events_map[event.category.title] = events

    results = merge_list(*events_map.values())

    date_events = results[page * limit: (page + 1) * limit]
    return JsonResponse({'data': SDEventSeri(date_events, many=True).data, 'code': 0})
